{% extends "base.html" %}

{% load staticfiles %}

{% block title %}DAMN - upload{% endblock %}

{% block head %}
<link href="{% static "ajax-upload/fileuploader.css" %}" rel="stylesheet" type="text/css">
    
    <script src="{% static "ajax-upload/fileuploader.js" %}" type="text/javascript"></script>

	<script type="text/javascript">
	  $(document).ready(function () {
	  
	    var MetaData = function (metadata){
	      var text = '<ul>';
        for (m in metadata) 
          text += '<li>'+m +': '+ metadata[m]+'</li>';
        text += '</ul>';
        return text;
	    };
	    
	    var Dependencies = function (ass, fileRef, asset, dependencies){
	      this.element = $('<ul></ul>');
        for (d in dependencies) {
          var dep = dependencies[d];
          var li = $('<li>'+dep.subName + ' ('+dep.format+')</li>');
          if (dep.brokenReference){
            li.addClass('error');
            var select = $('<select></select>');
            li.append(select);
            $.getJSON('/api/files/upload/assets/exclude/'+fileRef.hash+'/'+asset.subName+'/'+asset.format+'/', function(data){
              if (data.length) {
                jQuery.each(data, function(nr, a) {
                    var option = $('<option></option>');
                    option.attr('hash', a.file);
                    option.attr('subName', a.subName);
                    option.attr('format', a.format);
                    select.append(option.val(a.subName).html(a.subName));
                });
                var button = $('<input type="button" value="update"></input>');
                li.append(button);
                button.click(function(){
                  var postData = {};
                  postData['srchash'] = fileRef.hash;
                  postData['srcSubName'] = asset.subName;
                  postData['srcFormat'] = asset.format;
                  
                  postData['dephash'] = dep.file;
                  postData['depSubName'] = dep.subName;
                  postData['depFormat'] = dep.format;
                   
                  postData['newDephash'] = select.find('option:selected').attr('hash');
                  postData['newDepSubName'] = select.find('option:selected').attr('subName');
                  postData['newDepFormat'] = select.find('option:selected').attr('format');
                  $.post("/api/files/upload/relink/", postData, function(data) {
                    ass.Update(true);
                  });
                });
              } else {
                select.replaceWith('<span> No available options</span>');
              }
            });
          }
          this.element.append(li);
        }
	    };
	  
	    var Asset = function (fileRef, asset){
	      this.fileRef = fileRef;
	      this.asset = asset;
	      
	      this.element = $('<li style="border: 1px solid black;"></li>');
	      var text = '<li style="border: 1px solid black;"><table>';
	      text += '<div>'+asset.subName + ' ('+asset.format+') brokenReference: '+asset.brokenReference+'</div>';
	      text += '<tr valign="top">';
	      text += '<td><ul>';
	        text += '<li><div>Metadata:</div>';
	        text += '<div class="meta"></div>';
	        text += '</li>';
	        text += '<li><div>Dependencies:</div>';
	        text += '<div class="deps"></div>';
	        text += '</li>';
	      text += '</ul></td>';
	      if (!asset.brokenReference) {
          text += '<td><img style="float: left;"></img></td>';
        } else {
          text += 'No Preview, cause you know it isnt there!';
        }
        text += '</tr>';
	      text += '</table>';
	      this.element.html(text);
	      
	      this.DrawMeta = function(){
	        this.element.find('.meta').empty();
	        this.element.find('.meta').html(MetaData(this.asset.metadata));
	      }
	      
	      this.DrawImage = function(fetch){
	        var src = '/api/files/upload/'+fileRef.hash+'/'+asset.subName+'/'+asset.format+'/transcode/?sizex=256&sizey=256';
	        if (fetch) {
	          var d = new Date();
	          src += '&noCache='+d.toString();
	        }
	        this.element.find('img').attr('src', src);
	      }
	      
	      this.DrawDependencies = function(){
	        this.element.find('.deps').empty();
	        this.dependencies = new Dependencies(this, fileRef, this.asset, this.asset.dependencies);
	        this.element.find('.deps').append(this.dependencies.element);
	      }
	      
	      this.Update = function(fetch){
	        var self = this;
	        if (fetch) {
	          $.getJSON('/api/files/upload/assets/'+fileRef.hash+'/'+this.asset.subName+'/'+this.asset.format, function(data){
	            self.asset = data;
	            self.DrawMeta();
	            self.DrawDependencies();
	            self.DrawImage(true);
	          });
	        } else {
	          this.DrawMeta();
	          this.DrawDependencies();
	          this.DrawImage();
	        }
	      };
	    };
	    
	    var assets = [];
                
      var uploader = new qq.FileUploader({
                element: document.getElementById('file-uploader'),
                action: '/api/files/aupload/',
                listElement: document.getElementById('assets'),
                debug: true,
                onComplete: function( id, fileName, responseJSON ) {
                  var div = $('<div></div>');
                  $('#assets').find('.qq-upload-file:contains('+fileName+')').parent().append(div);
                  if( responseJSON.success ){
                    var text = $('<div>'+responseJSON.fileRef.fileName +' - '+ responseJSON.fileRef.hash+'</div>');
                    div.append(text);
                    var ul = $('<ul></ul>');
                    for (a in responseJSON.fileRef.assets){ 
                      var asset = responseJSON.fileRef.assets[a];
                      var a = new Asset(responseJSON.fileRef, asset);
                      assets.push(a);
                      ul.append(a.element);
                    }
                    div.append(ul);
                    for (a in assets){
                      assets[a].Update();
                    }
                  }
                  else {
                    div.html(responseJSON.error);
                  }
                }
            });   
   	});
	</script>
	
	<style>
        .drop-zone {width:256px; background:gray; margin:20px;}
        .qq-upload-button {
            display:block; /* or inline-block */
            width: auto; padding: 7px 0; text-align:center;    
            background:#880000; border-bottom:1px solid #ddd;color:#fff;
        }
        .qq-upload-drop-area {
            min-height: 220px;
        }
        .error {
          color: red;
        }
    </style>
{% endblock %}

{% block left %}
  Drag and drop files on the red button or click it to select files.
{% endblock %}


{% block right %}
<div class="drop-zone">
    <div id="file-uploader">		
		  <noscript>			
			  <p>Please enable JavaScript to use file uploader.</p>
			  <!-- or put a simple form for upload here -->
		  </noscript>         
	  </div>
	</div>
	
	<div id="assets-wrapper">
	  <ul id="assets"></ul>
	</div>
{% endblock %}
